<template>
  <div class="group-card" :class="cardClass" @click="handleCardClick">
    <!-- 小组头部 -->
    <div class="group-header">
      <!-- 小组封面 -->
      <div v-if="group.coverImage" class="group-cover">
        <img :src="group.coverImage" :alt="group.name || '小组封面'" />
      </div>
      
      <!-- 小组基本信息 -->
      <div class="group-info">
        <!-- 小组名称和类型 -->
        <div class="group-name-section">
          <h3 class="group-name">{{ group.name || '未命名小组' }}</h3>
          <el-tag v-if="group.type" :type="getGroupTypeTag()" size="small">{{ getGroupTypeText() }}</el-tag>
        </div>
        
        <!-- 小组简介 -->
        <p v-if="group.description" class="group-description">{{ truncateDescription(group.description) }}</p>
        
        <!-- 小组统计 -->
        <div class="group-stats">
          <div class="stat-item">
            <span class="stat-label">成员</span>
            <span class="stat-value">{{ group.memberCount || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">活动</span>
            <span class="stat-value">{{ group.activityCount || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">资源</span>
            <span class="stat-value">{{ group.resourceCount || 0 }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 小组内容 -->
    <div class="group-content">
      <!-- 最新活动 -->
      <div v-if="showLatestActivity && group.latestActivity" class="latest-activity">
        <h4 class="section-title">最新活动</h4>
        <div class="activity-info">
          <span class="activity-icon">
            <el-icon><Calendar /></el-icon>
          </span>
          <span class="activity-name">{{ group.latestActivity.title }}</span>
          <span class="activity-time">{{ group.latestActivity?.startTime ? formatDate(group.latestActivity.startTime as string, 'MM-DD') : '-' }}</span>
        </div>
      </div>
      
      <!-- 成员头像 -->
      <div v-if="showMemberAvatars && group.members && group.members.length > 0" class="member-avatars">
        <h4 class="section-title">成员</h4>
        <div class="avatars-container">
          <div
            v-for="(member, index) in displayedMembers"
            :key="index"
            class="member-avatar"
            :title="member.user?.username || '成员'"
          >
            <img :src="member.user?.avatar || defaultAvatar" :alt="member.user?.username || '成员头像'" />
            <div v-if="member.role === 'ADMIN' || member.role === 'owner'" class="role-badge owner">
              <el-icon><User /></el-icon>
            </div>
            <div v-else-if="member.role === 'MODERATOR' || member.role === 'manager'" class="role-badge manager">
              <el-icon><Management /></el-icon>
            </div>
          </div>
          <div v-if="hasMoreMembers" class="member-more">
            +{{ group.members.length - maxDisplayMembers }}
          </div>
        </div>
      </div>
      
      <!-- 自定义内容 -->
      <div v-if="$slots.content" class="group-custom-content">
        <slot name="content" :group="group" />
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div v-if="showActions" class="group-actions">
      <button
        v-if="!isJoined && !isRequesting"
        class="action-btn action-join"
        @click.stop="handleJoin"
        :disabled="isJoining"
      >
        <span v-if="!isJoining">加入小组</span>
        <span v-else>加入中...</span>
      </button>
      <button
        v-if="isJoined"
        class="action-btn action-joined"
        @click.stop="handleView"
      >
        进入小组
      </button>
      <button
        v-if="isRequesting"
        class="action-btn action-pending"
        @click.stop="handleCancelRequest"
      >
        申请中
      </button>
      <button
        v-if="canManage"
        class="action-btn action-manage"
        @click.stop="handleManage"
      >
        管理小组
      </button>
      <button
        v-if="canEdit"
        class="action-btn action-edit"
        @click.stop="handleEdit"
      >
        编辑
      </button>
      <button
        v-if="canDelete"
        class="action-btn action-delete"
        @click.stop="handleDelete"
      >
        删除
      </button>
    </div>
    
    <!-- 小组状态标签 -->
    <div v-if="group.status !== 'active'" class="group-status-badge" :class="`status-${group.status}`">
      {{ getStatusText() }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, withDefaults, defineProps, defineEmits, defineExpose } from 'vue'
import { useRouter } from 'vue-router'
import type { StudyGroup, GroupMember, GroupActivity } from '../types/group'
import { ElTag, ElIcon } from 'element-plus'
import {
  Calendar,
  User,
  Management
} from '@element-plus/icons-vue'
import { formatDate, truncateString as truncateText } from '../utils/common'

// 默认头像
const defaultAvatar = '/default-avatar.png'

// Props
interface Props {
  group: Partial<StudyGroup & {
    memberCount?: number
    activityCount?: number
    resourceCount?: number
    members?: Partial<GroupMember>[]
    latestActivity?: Partial<GroupActivity>
    coverImage?: string
    type?: string
    status?: string
    user?: any
  }>
  currentUserId?: string | number
  isJoined?: boolean
  isRequesting?: boolean
  canJoin?: boolean
  canManage?: boolean
  canEdit?: boolean
  canDelete?: boolean
  showLatestActivity?: boolean
  showMemberAvatars?: boolean
  showActions?: boolean
  size?: 'small' | 'medium' | 'large'
  maxDisplayMembers?: number
}

const props = withDefaults(defineProps<Props>(), {
  group: () => ({}),
  isJoined: false,
  isRequesting: false,
  canJoin: true,
  canManage: false,
  canEdit: false,
  canDelete: false,
  showLatestActivity: true,
  showMemberAvatars: true,
  showActions: true,
  size: 'medium',
  maxDisplayMembers: 5
})

// Router
const router = useRouter()

// Emits
const emit = defineEmits<{
  'join': [group: Partial<StudyGroup>]
  'leave': [group: Partial<StudyGroup>]
  'view': [group: Partial<StudyGroup>]
  'manage': [group: Partial<StudyGroup>]
  'edit': [group: Partial<StudyGroup>]
  'delete': [group: Partial<StudyGroup>]
  'cancelRequest': [group: Partial<StudyGroup>]
}>()

// Refs
const isJoining = ref(false)

// 计算属性
const cardClass = computed(() => {
  return [
    `group-card-${props.size}`,
    {
      'group-card-private': props.group.type === 'private',
      'group-card-public': props.group.type === 'public',
      'group-card-verified': props.group.isVerified
    }
  ]
})

// 显示的成员数量
const displayedMembers = computed(() => {
  return props.group.members?.slice(0, props.maxDisplayMembers) || []
})

// 是否有更多成员
const hasMoreMembers = computed(() => {
  return props.group.members && props.group.members.length > props.maxDisplayMembers
})

// 获取小组类型文本
const getGroupTypeText = () => {
  const typeMap: Record<string, string> = {
    'public': '公开小组',
    'private': '私有小组',
    'professional': '专业小组'
  }
  return typeMap[props.group.type as string] || '普通小组'
}

// 获取小组类型标签样式
const getGroupTypeTag = (): "primary" | "success" | "warning" | "info" | "danger" => {
  const typeMap: Record<string, "primary" | "success" | "warning" | "info" | "danger"> = {
    'public': 'success',
    'private': 'info',
    'professional': 'primary'
  }
  return typeMap[props.group.type as string] || "info"
}

// 获取小组状态文本
const getStatusText = () => {
  const statusMap: Record<string, string> = {
    'pending': '审核中',
    'active': '活跃',
    'inactive': '非活跃',
    'archived': '已归档'
  }
  return statusMap[props.group.status as string] || '未知状态'
}

// 截断描述文本
const truncateDescription = (description: string) => {
  return truncateText(description, 100)
}

// 事件处理
const handleCardClick = () => {
  if (props.group.id) {
    // 跳转到小组详情页
    router.push(`/group/${props.group.id}`)
  }
}

const handleJoin = async () => {
  if (isJoining.value) return
  
  isJoining.value = true
  try {
    emit('join', props.group)
  } finally {
    // 实际项目中，这里会根据API响应来决定是否设置为已加入状态
    // 模拟加入成功后更新状态
    // setTimeout(() => {
    //   isJoining.value = false
    // }, 1000)
  }
}

const handleView = () => {
  emit('view', props.group)
}

const handleManage = () => {
  emit('manage', props.group)
}

const handleEdit = () => {
  emit('edit', props.group)
}

const handleDelete = () => {
  emit('delete', props.group)
}

const handleCancelRequest = () => {
  emit('cancelRequest', props.group)
}

// 暴露方法
defineExpose({
  join: handleJoin,
  view: handleView,
  manage: handleManage,
  setIsJoining: (status: boolean) => {
    isJoining.value = status
  }
})
</script>

<style scoped>
.group-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
}

.group-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

/* 尺寸样式 */
.group-card-small {
  padding: 0;
}

.group-card-medium {
  padding: 0;
}

.group-card-large {
  padding: 0;
}

/* 小组头部 */
.group-header {
  position: relative;
}

.group-cover {
  width: 100%;
  height: 120px;
  overflow: hidden;
  position: relative;
}

.group-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.group-card:hover .group-cover img {
  transform: scale(1.05);
}

.group-info {
  padding: 16px;
}

.group-name-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.group-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  flex: 1;
  margin-right: 8px;
}

.group-description {
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
  margin: 8px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.group-stats {
  display: flex;
  justify-content: space-between;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
  margin-top: 8px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-value {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 小组内容 */
.group-content {
  padding: 0 16px 16px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

/* 最新活动 */
.latest-activity {
  margin-bottom: 12px;
}

.activity-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.activity-icon {
  color: #409eff;
}

.activity-name {
  flex: 1;
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.activity-time {
  font-size: 12px;
  color: #909399;
}

/* 成员头像 */
.member-avatars {
  margin-bottom: 12px;
}

.avatars-container {
  display: flex;
  align-items: center;
  gap: -8px;
  padding: 4px 0;
}

.member-avatar {
  position: relative;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.member-avatar:hover {
  transform: scale(1.1);
  z-index: 10;
}

.member-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.role-badge {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.role-badge.owner {
  background-color: #f56c6c;
}

.role-badge.manager {
  background-color: #409eff;
}

.role-badge.el-icon {
  width: 12px;
  height: 12px;
  color: #fff;
}

.member-more {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #f0f2f5;
  font-size: 12px;
  font-weight: 500;
  color: #606266;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 操作按钮 */
.group-actions {
  display: flex;
  justify-content: center;
  gap: 8px;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-top: 1px solid #f0f2f5;
}

.action-btn {
  padding: 6px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.action-join {
  background-color: #409eff;
  color: white;
}

.action-join:hover:not(:disabled) {
  background-color: #66b1ff;
}

.action-join:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.action-joined {
  background-color: #67c23a;
  color: white;
}

.action-joined:hover {
  background-color: #85ce61;
}

.action-pending {
  background-color: #e6a23c;
  color: white;
}

.action-pending:hover {
  background-color: #ebb563;
}

.action-manage {
  background-color: #909399;
  color: white;
}

.action-manage:hover {
  background-color: #a6a9ad;
}

.action-edit {
  background-color: #606266;
  color: white;
}

.action-edit:hover {
  background-color: #73767a;
}

.action-delete {
  background-color: #f56c6c;
  color: white;
}

.action-delete:hover {
  background-color: #f78989;
}

/* 小组状态标签 */
.group-status-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: white;
  z-index: 10;
}

.status-pending {
  background-color: #e6a23c;
}

.status-active {
  background-color: #67c23a;
}

.status-inactive {
  background-color: #909399;
}

.status-archived {
  background-color: #f56c6c;
}

/* 小组类型特殊样式 */
.group-card-private::before {
  content: '';
  position: absolute;
  top: 12px;
  left: 12px;
  width: 24px;
  height: 24px;
  background-color: rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.group-card-private::before {
  content: '🔒';
  font-size: 14px;
}

.group-card-verified::after {
  content: '✓';
  position: absolute;
  top: 12px;
  left: 48px;
  width: 24px;
  height: 24px;
  background-color: rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  color: #409eff;
  z-index: 10;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .group-cover {
    height: 100px;
  }
  
  .group-info {
    padding: 12px;
  }
  
  .group-name {
    font-size: 16px;
  }
  
  .group-actions {
    flex-wrap: wrap;
    padding: 12px;
  }
  
  .action-btn {
    flex: 1;
    min-width: 45%;
  }
}

@media (max-width: 480px) {
  .group-cover {
    height: 80px;
  }
  
  .group-name-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .group-stats {
    flex-direction: column;
    gap: 8px;
  }
  
  .stat-item {
    text-align: left;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>